<?php
class longModel extends appModel{
    
    private $appid = "wxc59074e82da37239";
    private $appSecret = "c6cb2b54e28e38dd7cff2d426460303c";
    
    public function is_save_openid($openid)
	{
		$sql = "select count(*) from ".$this->table('long_users')." where openid='".$openid."'";
		return $this->getOne($sql);
	}
    
	public function getPrize2($openid,$card_type)
	{
	    $id = 0;$prize=array();
	    //判断用户
	    $sql = "SELECT p2.mark,p1.addtime,p1.pid,p1.ppid,p1.id,p1.is_card,p2.prize_name,p2.card_id,p1.id as user_id FROM ".$this->table('long_prize_user')." as p1 LEFT JOIN ".
	        $this->table('long_prize').' as p2 ON p1.pid = p2.id '.
	        " WHERE openid='".$openid."' and p2.card_type = '".$card_type."'".
	        " ORDER BY addtime desc LIMIT 1 ";
	    $res = $this->getRow($sql);
	    if(!$res){//未抽过奖
	        //在时间段内可抽取的奖项
	        $sql3 = 'SELECT p1.pid,p1.id,p1.prizenums,p1.nums,p2.pby,p2.card_id FROM '.$this->table('long_prize_period').' as p1 LEFT JOIN '.
	            $this->table('long_prize').' as p2 ON p1.pid = p2.id '.
	            ' WHERE begintime<'.yf_time().' and endtime>'.yf_time().' and p1.nums>p1.prizenums and p2.card_type = '.$card_type.' order by p2.pri desc  '  ;
	        $result3 = $this->getAll($sql3);
	        if($result3){
	            foreach($result3 as $k =>$v){
	                 
	                if(rand(1,100) < $v['pby']){
	                    $id = $v['pid'];            //奖项id
	                    $period_id = $v['id'];      //奖项时间段id
	                    $temp_k = $v;
	                    break;
	                }
	            }
	        }
	             
	        
	    }else{//有记录
	        $lottery = $res['addtime'];
	        if(date("Y-m-d",$lottery)==date("Y-m-d",time())){//相等
	            if($res['is_card'] == 0){//未领取
	                $id = $res['pid'];
	                $temp_k['prize_name'] = $res['prize_name'];
	                $temp_k['mark'] = $res['mark'];
	                $temp_k['card_id'] = $res['card_id'];
	                $prize['user_id'] = $res['user_id'];
	                
	            }else{//当天已经领取
	                return array();
	            }
	            
	        }else{//重新抽奖
	            //在时间段内可抽取的奖项
	            $sql3 = 'SELECT p1.pid,p1.id,p1.prizenums,p1.nums,p2.pby,p2.card_id,p2.prize_name FROM '.$this->table('long_prize_period').' as p1 LEFT JOIN '.
	                $this->table('long_prize').' as p2 ON p1.pid = p2.id '.
	                ' WHERE begintime<'.yf_time().' and endtime>'.yf_time().' and p1.nums>p1.prizenums and p2.card_type = '.$card_type.' order by p2.pri desc  '  ;
	            $result3 = $this->getAll($sql3);
	            if($result3){
	                foreach($result3 as $k =>$v){
	            
	                    if(rand(1,100) < $v['pby']){
	                        $id = $v['pid'];            //奖项id
	                        $period_id = $v['id'];      //奖项时间段id
	                        $temp_k = $v;
	                        break;
	                    }
	                }
	            }
	        }
	    }
	    
	    //中奖
	    if($id!=0){//拿到的奖项
	        $prize['prize_name'] = $temp_k['prize_name'];
	        $prize['mark'] = $temp_k['mark'];
	        $prize['card_id'] = $temp_k['card_id'];
	        $sql2 = 'SELECT id,is_card FROM '.$this->table('long_prize_user').' WHERE pid="'.$id.'" and openid="'.$openid.'" LIMIT 1 ';
	        $res2 = $this->getRow($sql2);
	    
	        if(!$res2)
	        {
	    
	            $this->setInc("prizenums", 1, "long_prize", $id);
	    
	            $this->setInc("prizenums", 1, "long_prize_period", $period_id);
	    
	    
	            $info['wxid'] = $this->getUserIdbyopenid($openid);
	            $info['pid'] = $id;
	            $info['ppid'] = $period_id;
	            $info['addtime'] = time();
	            $info['openid'] = $openid;
	    
	            $user_id = $this->insert($info, 'long_prize_user');
	            $prize['user_id'] = $user_id;
	            $prize['is_card'] = 0;
	    
	        }
	    
	    }
	    
	    return $prize;
	    
	}
	
	public function updateInfo($info,$cfg)
	{
        foreach($info as $k=>$v)
        {

            $set.=" $k='$v',";


        }
        $set=substr($set,0,strlen($set)-1);
        
        $t=$cfg['table'];
        unset($cfg['table']);
        $where=" WHERE 1=1 AND ";
        $logic=" AND ";
        foreach($cfg as $k=>$v)
        {
            if(is_array($v))
            {
                $where.="".$k." in (".implode(',',$v).")".$logic;
            }
            else
            {
                $where.=" ".$k."='".$v."'".$logic;
            }
        }
        
        $where=$where."1=1";
        
        $sql="UPDATE ".$this->table($t)." SET ".$set." $where ";
        return $res=$this->query($sql);
	}
	
	public function isSaved($openid)
	{
	    $sql = "SELECT telphone FROM ".$this->table("long_users")." WHERE openid = '$openid' LIMIT 1 ";
	    $tel = $this->getOne($sql);
	    if(empty($tel)){
	        return false;
	    }else{
	        return true;
	    }
	}
	
	public function getCard($openid)
	{
	    $sql = "SELECT p1.id,p2.card_id FROM ".$this->table("long_prize_user")." p1 LEFT JOIN ".$this->table('long_prize')." p2  ON p1.pid = p2.id WHERE p1.openid = '$openid' AND p1.is_card = 0 ORDER BY addtime DESC LIMIT 1 ";
	    $card = $this->getRow($sql);
	    if(empty($card)){
	        return false;
	    }else{
	        $cards = explode(",",$card['card_id']);
            if(is_array($cards))
            {
                foreach ($cards as $k => $v)
                    {
                        $card_list[]['cardId'] = $v;
                    }
            }
            else
            {
                $card_list[]['cardId'] = $card['card_id'];
            }
            $jsdk_card = $this->build_jsdk_card($card_list);
            $card['jsdk_card'] = $jsdk_card;
            return $card;
	    }
	}
	
	public function saveCard($id)
	{
	     
	    $this->setInc("is_card", 1, "long_prize_user", $id);
	     
	}
	
	public function getPrize($openid,$card_type)
	{
	    $prize = array();
	    $id = 0;                    //奖项id
	    $prize['user_id'] = 0;      // chenzhan_prize_user 用户中奖记录id
	    $where = " WHERE 1=1 ";
	    $result = "";
	
	    //最近一条中奖记录
	    $sql_1 = 'SELECT p2.mark,p1.addtime,pid,ppid,p1.id,p1.is_card,p2.prize_name,p2.card_id FROM '.$this->table('long_prize_user')." as p1 LEFT JOIN ".
	        $this->table('long_prize').' as p2 ON p1.pid = p2.id '.
	        " WHERE openid='".$openid."' and p2.card_type = '".$card_type."'".
	        " ORDER BY addtime desc LIMIT 1 ";
	    $res = $this->getRow($sql_1);
	
	     
	    if(!$res){
	        $res_1 = 0;
	    }
	    else
	    {
            //最近一条中奖记录
            $res_1 = $res['addtime'];
            $id = $res['pid'];
            if($res['is_card'] == 0){//未领取情况
                $prize['prize_name'] = $res['prize_name'];
                $prize['mark'] = $res['mark'];
                $prize['user_id'] = $res['id'];
                $prize['is_card'] = $res['is_card'];
                $prize['card_id'] = $res['card_id'];
            }
	    }
	
	    $res_1 = date("Y-m-d",$res_1);
	    $new = date("Y-m-d",time());
	
	
	    //一天只能中一次奖
	    if($res_1 != $new){//重新抽奖
	        $id = 0;
	        //当天没有中过奖
	        //在时间段内可抽取的奖项
	        $sql3 = 'SELECT p1.pid,p1.id,p1.prizenums,p1.nums,p2.pby,p2.card_id FROM '.$this->table('long_prize_period').' as p1 ,'.
	            $this->table('long_prize').' as p2 '.
	            ' WHERE begintime<'.yf_time().' and endtime>'.yf_time().' and p1.nums>p1.prizenums and p1.pid = p2.id and p2.card_type = '.$card_type.' order by p2.pri desc  '  ;
	
	        $result3 = $this->getAll($sql3);
	
	        if($result3){
	
	            foreach($result3 as $k =>$v){
	
	                if(rand(1,100) < $v['pby']){
	                    $id = $v['pid'];            //奖项id
	                    $period_id = $v['id'];      //奖项时间段id
	                    $temp_k = $v;
	                    break;
	                }
	            }
	
	            //中奖
	            if($id!=0){
	
	                $prize['prize_name'] = $temp_k['prize_name'];
	                $prize['mark'] = $temp_k['mark'];
	                $prize['card_id'] = $res['card_id'];
	                
	                $sql2 = 'SELECT id,is_card FROM '.$this->table('long_prize_user').' WHERE pid="'.$id.'" and openid="'.$openid.'"';
	                $res2 = $this->getRow($sql2);
	
	                if(!$res2)
	                {
	                    //                      //新中奖记录
	
	                    $this->setInc("prizenums", 1, "long_prize", $id);
	
	                    $this->setInc("prizenums", 1, "long_prize_period", $period_id);
	                     
	                     
	                    $info['wxid'] = $this->getUserIdbyopenid($openid);
	                    $info['pid'] = $id;
	                    $info['ppid'] = $period_id;
	                    $info['addtime'] = time();
	                    $info['openid'] = $openid;
	
	                    $user_id = $this->insert($info, 'long_prize_user');
	                    $prize['user_id'] = $user_id;
	                    $prize['is_card'] = 0;
	
	                }
	
	            }else{
	                $prize = array();
	            }
	
	        }
	    }
	
	
	    return $prize;
	}
	
	public function getUserIdbyopenid($openid)
	{
	    $sql = "SELECT id FROM ".$this->table("long_users")." WHERE openid = '$openid' LIMIT 1";
	    return $this->getOne($sql);
	}
	
	public function setInc($field,$step,$table,$id)
	{
	
	
	    $sql = " update ".$this->table($table)." set ".$field." = ".$field." + ".$step." where id = '".$id."'";
	
	    return $this->query($sql);
	}
	
    public function getAccessTokenLong()
    {
    
        $path = ROOT_PATH."/Qiaqia/Json/long_access_token.json";
        $data = json_decode(file_get_contents($path), true);
        if(empty($data['access_token']) || $data['expire_time'] < yf_time())
        {
            $app['appid'] = $this->appid;
            $app['appsecret'] = $this->appSecret;
            $new_info = Ctrl("weixin")->getToken($app['appid'], $app['appsecret']);
            $info['access_token'] = $new_info['access_token'];
            $info['expire_time'] = yf_time() + 1500;
            $fp = fopen($path, "w");
            fwrite($fp, json_encode($info));
            fclose($fp);
            return $new_info['access_token'];
        }
        else
        {
            Ctrl("weixin")->setToken($data['access_token']);
            return $data['access_token'];
        }
    }
    
    
    /**
     * 获取jsdk的参数
     * @author yf
     */
    public function get_jsdk_long()
    {
        $appid = $this->appid;
        $path = ROOT_PATH."/Qiaqia/Json/long_jsapi_ticket.json";
        $data = json_decode(file_get_contents($path), true);
    
        if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
        {
            $access_token = $this->getAccessTokenLong();
            $new_info = Ctrl("weixin")->getJsapiTicket($access_token);
            $info['jsapi_ticket'] = $new_info['ticket'];
            $info['expire_time'] = yf_time() + 1500;
            $fp = fopen($path, "w");
            fwrite($fp, json_encode($info));
            fclose($fp);
            $jsapi_ticket = $new_info['ticket'];
        }
        else
        {
            $jsapi_ticket = $data['jsapi_ticket'];
        }
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = yf_time();
        $nonceStr = $this->createNonceStrLong();
    
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }
    
    /**
     * 获取jsdk的参数
     * @author yf
     */
    public function build_jsdk_card($cardList)
    {
        $appid = $this->appid;
        $appSecret = $this->appSecret;
        $path = ROOT_PATH."Qiaqia/Json/long_jsapi_ticket_card.json";
    
        $data = json_decode(file_get_contents($path), true);
    
        if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
        {
    
            $access_token = $this->getAccessTokenLong();
            $new_info = Ctrl("weixin")->getCardapiTicket($access_token);
            $info['jsapi_ticket'] = $new_info['ticket'];
            $info['expire_time'] = yf_time() + 1500;
            $fp = fopen($path, "w");
            fwrite($fp, json_encode($info));
            fclose($fp);
            $api_ticket = $new_info['ticket'];
        }
        else
        {
            $api_ticket = $data['jsapi_ticket'];
        }
        $timestamp = yf_time();
    
        $cards = array();
    
        foreach ($cardList as $k=>$v)
        {
            $card = array();
    
            $cardId = $v['cardId'];
            $arrays = array($api_ticket,$timestamp,$cardId);
            sort($arrays , SORT_STRING);
    
            $string = implode($arrays);
            $signatureCard = sha1($string);
    
            $cardSignature = '{"code": "", "openid": "","timestamp":"'.$timestamp.'","signature":"'.$signatureCard.'"}';
    
            $card['cardId'] = $cardId;
            $card['cardExt'] = $cardSignature;
    
            $cards[] = $card;
        }
        	
        return $cards;
    }
    
    /**
     * jsdk获取字段
     * @param number $length
     * @return string
     */
    private function createNonceStrLong($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}